package 人手一支笔ThreadLock;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadLocalDemo {
    static ThreadLocal<SimpleDateFormat> threadLocal = new ThreadLocal<>();

    static class ParseDate implements Runnable{
        int i = 0;

        @Override
        public void run() {
            if (threadLocal.get() == null){
                threadLocal.set(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            }
            try {
                Date date = threadLocal.get().parse("2022-4-5 16:44:" + i % 60);
                System.out.println(i + ":" + date);
                threadLocal.remove();//一个线程用完就可以清理掉，不然可能内存泄漏！！
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 5; i++) {
            executorService.execute(new ParseDate());
        }
    }
}
